//
//  ContactListController.m
//  MClient
//
//  Created by zhouyi on 11-6-7.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactListController.h"
#import "MCSectionBar.h"
#import "MServerDAO.h"
#import "MCUIToolkit.h"

@implementation ContactListController
@synthesize remoteContacts, localContacts, contactId;

- (void)viewDidLoad {
	[super viewDidLoad];
	rightButtonControl = [[UISegmentedControl alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
	rightButtonControl.segmentedControlStyle = UISegmentedControlStyleBar;
	
	rightButtonControl.tintColor = [MCUserDefaults instance].skin_segmentedControlColor;
	[rightButtonControl addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventValueChanged];
	[rightButtonControl insertSegmentWithTitle:@"全选" atIndex:0 animated:NO];
	[rightButtonControl insertSegmentWithTitle:@"导入" atIndex:1 animated:NO];
	[rightButtonControl setEnabled:NO forSegmentAtIndex:1];
	rightButtonControl.momentary = YES;
	rightButtonControl.tag = -123;
	
	UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:rightButtonControl];
	//[rightButtonControl release];
	self.rightBarButtonItem = button;
	[button release]; button = nil;
	/*
	UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
	
	segmentedControl.tintColor = [MCUserDefaults instance].skin_segmentedControlColor;
	[segmentedControl addTarget:self action:@selector(changeSection:) forControlEvents:UIControlEventValueChanged];
	[segmentedControl insertSegmentWithTitle:@"远程通讯录" atIndex:0 animated:NO];
	[segmentedControl insertSegmentWithTitle:@"本地通讯录" atIndex:1 animated:NO];
	segmentedControl.selectedSegmentIndex = 0;
	segmentedControl.tag = -321;
	self.navigationItem.titleView = segmentedControl;
	[segmentedControl release];
	*/
	self.title = @"通讯录同步";
	self.tableview.frame = CGRectMake(0, nToolBarHeight, self.width, self.height-nToolBarHeight);
	MCSectionBar *sectionBar = [[MCSectionBar alloc] initWithFrame:CGRectMake(0, 0, self.width, nToolBarHeight)];
	sectionBar.autoresizingMask = nMCViewAutoresizingMask;
	sectionBar.tag = -321;
	//NSMutableArray *sections = [NSMutableArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"远程通讯录", @"lbl", nil],[NSDictionary dictionaryWithObjectsAndKeys:@"本地通讯录", @"lbl", nil], nil];//huotianjun 注释掉，去掉本地通信录
    NSMutableArray *sections = [NSMutableArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"远程通讯录", @"lbl", nil], nil];
	[sectionBar addSectionBarItems:sections delegate:self];
	[self.clientView addSubview:sectionBar];
	[sectionBar release];
	 
	//localContacts = [[NSMutableArray alloc] init];//huotianjun注释掉
	selectedRemoteContacts = [[NSMutableArray alloc] init];
	//selectedLocalContacts = [[NSMutableArray alloc] init];//huotianjun注释掉
}

-(void)changeOperationState {
	if(tabIndex == 0) {
		if([selectedRemoteContacts count] > 0) {
			[rightButtonControl setEnabled:YES forSegmentAtIndex:1];
		} else {
			[rightButtonControl setEnabled:NO forSegmentAtIndex:1];
		}
	} else {
		if([selectedLocalContacts count] > 0) {
			[rightButtonControl setEnabled:YES forSegmentAtIndex:1];
		} else {
			[rightButtonControl setEnabled:NO forSegmentAtIndex:1];
		}
	}
}

-(void)changeSection:(id)sender {
	tabIndex = [sender selectedSegmentIndex];
	if (tabIndex == 0) {
		//UIBarButtonItem *segmentBarItem = (UIBarButtonItem*)self.rightBarButtonItem;
		//UISegmentedControl *rightButtonControl = (UISegmentedControl*)segmentBarItem.customView;
		[rightButtonControl setTitle:@"导入" forSegmentAtIndex:1];
	}else {
		//获取本地通讯录
		[localContacts removeAllObjects];
		ABAddressBookRef addressBook = ABAddressBookCreate();
		
		NSArray *peopleArray = (NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
		for (int i = 0; i < [peopleArray count]; i++) {
			NSMutableDictionary *localContact = [NSMutableDictionary dictionary];
			NSMutableDictionary *datas = [NSMutableDictionary dictionary];
			
			ABRecordRef people = (ABRecordRef)[peopleArray objectAtIndex:i];
			ABMultiValueRef firstName = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonFirstNameProperty);
			ABMultiValueRef lastName = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonLastNameProperty);
			NSMutableString *strName = [NSMutableString string];
			if (firstName) [strName appendFormat:@"%@", firstName];
			if (lastName) [strName appendFormat:@"%@", lastName];
			
			NSMutableDictionary *fieldData = [NSMutableDictionary dictionary];
			[fieldData setObject:[NSString stringWithFormat:@"%@", strName] forKey:@"value"];
			[datas setObject:fieldData forKey:@"name"];
			
			ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonPhoneProperty);
			for (int j = 0; j < ABMultiValueGetCount(phones); j++) {
				NSString *phoneNO = (NSString *)ABMultiValueCopyValueAtIndex(phones, j);
				NSString *phoneLabel = (NSString *)ABMultiValueCopyLabelAtIndex(phones, j);
				if ([phoneLabel isEqualToString:[NSString stringWithFormat:@"%@", kABPersonPhoneMobileLabel]]) {
					NSMutableDictionary *fieldData = [NSMutableDictionary dictionary];
					[fieldData setObject:phoneNO forKey:@"value"];
					[datas setObject:fieldData forKey:@"mobile_tel"];
				} else if ([phoneLabel isEqualToString:[NSString stringWithFormat:@"%@", kABHomeLabel]]) {
					NSMutableDictionary *fieldData = [NSMutableDictionary dictionary];
					[fieldData setObject:phoneNO forKey:@"value"];
					[datas setObject:fieldData forKey:@"home_tel"];
				} else if ([phoneLabel isEqualToString:[NSString stringWithFormat:@"%@", kABWorkLabel]]) {
					NSMutableDictionary *fieldData = [NSMutableDictionary dictionary];
					[fieldData setObject:phoneNO forKey:@"value"];
					[datas setObject:fieldData forKey:@"work_tel"];
				}
			}		
			ABMultiValueRef emails = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonEmailProperty);
			for (int j = 0; j < ABMultiValueGetCount(emails); j++) {
				NSString *emailValue = (NSString *)ABMultiValueCopyValueAtIndex(emails, j);
				if (j == 0) {
					NSMutableDictionary *fieldData = [NSMutableDictionary dictionary];
					[fieldData setObject:emailValue forKey:@"value"];
					[datas setObject:fieldData forKey:@"e-mail"];
				}
			}
			[localContact setObject:datas forKey:@"data"];
			[localContacts addObject:localContact];
		}
		[peopleArray release];
		CFRelease(addressBook);
		//UIBarButtonItem *segmentBarItem = (UIBarButtonItem*)self.rightBarButtonItem;
		//UISegmentedControl *rightButtonControl = (UISegmentedControl*)segmentBarItem.customView;
		[rightButtonControl setTitle:@"上传" forSegmentAtIndex:1];
	}
	[self.tableview reloadData];
	[self changeOperationState];
}

- (void)dealloc {
	[rightButtonControl release];
	[remoteContacts release];
	[localContacts release];
	[selectedRemoteContacts release];
	[selectedLocalContacts release];
	[contactId release];
	[operateType release];
    [super dealloc];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (tabIndex == 0) {
		return [remoteContacts count];
	}else {
		return [localContacts count];
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString *identifier = [NSString stringWithFormat:@"ContactTableCell-%d-%d", tabIndex, indexPath.row];
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
	if (nil == cell) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identifier] autorelease];
	}
	NSString *name;
	NSString *mobile_tel;
	if (tabIndex == 0) {
		NSMutableDictionary *remoteContact = [[remoteContacts objectAtIndex:indexPath.row] objectForKey:@"data"];
		name = [[remoteContact objectForKey:@"name"] objectForKey:@"value"]; 
		mobile_tel = [[remoteContact objectForKey:@"mobile_tel"] objectForKey:@"value"]; 
		bool flag = YES;
		for (NSMutableDictionary *selectContact in selectedRemoteContacts) {
			if ([selectContact isEqualToDictionary:[remoteContacts objectAtIndex:indexPath.row]]) {
				cell.accessoryType = UITableViewCellAccessoryCheckmark;
				flag = NO;
				break;
			}
		}
		if (flag) {
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
	} else {
		NSMutableDictionary *localContact = [[localContacts objectAtIndex:indexPath.row] objectForKey:@"data"];
		name = [[localContact objectForKey:@"name"] objectForKey:@"value"];
		mobile_tel = [[localContact objectForKey:@"mobile_tel"] objectForKey:@"value"]; 
		bool flag = YES;
		for (NSMutableDictionary *selectContact in selectedLocalContacts) {
			if ([selectContact isEqualToDictionary:[localContacts objectAtIndex:indexPath.row]]) {
				cell.accessoryType = UITableViewCellAccessoryCheckmark;
				flag = NO;
				break;
			}
		}
		if (flag) {
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
	}	
	
	UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:tabIndex * 1000 + 1];
	if (nil == nameLabel) {
		nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 6, 100, 32)];
		nameLabel.tag = tabIndex * 1000 + 1;
		nameLabel.font = [UIFont boldSystemFontOfSize:18];
		[cell.contentView addSubview:nameLabel];
		[nameLabel release];
	}
	nameLabel.text = name;
	
	UILabel *mobileTelLabel = (UILabel *)[cell.contentView viewWithTag:tabIndex * 1000 + 2];
	if (nil == mobileTelLabel) {
		mobileTelLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width - 150, 6, 130, 32)];
		mobileTelLabel.tag = tabIndex * 1000 + 2;
		mobileTelLabel.font = [UIFont systemFontOfSize:16];
		[cell.contentView addSubview:mobileTelLabel];
		[mobileTelLabel release];
	}
	mobileTelLabel.text = mobile_tel;
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	if (tabIndex == 0) {
		if (cell.accessoryType == UITableViewCellAccessoryNone) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			NSMutableDictionary *selectedContacts = [[remoteContacts objectAtIndex:indexPath.row] copy];
			[selectedRemoteContacts addObject:selectedContacts];
			[selectedContacts release];
		}else {
			for (int i = 0; i < [selectedRemoteContacts count]; i++) {
				NSMutableDictionary *contact = [selectedRemoteContacts objectAtIndex:i];
				if ([contact isEqualToDictionary:[remoteContacts objectAtIndex:indexPath.row]]) {
					[selectedRemoteContacts removeObjectAtIndex:i];
					break;
				}
			}
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
	} else {
		if (cell.accessoryType == UITableViewCellAccessoryNone) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			NSMutableDictionary *selectedContacts = [[localContacts objectAtIndex:indexPath.row] copy];
			[selectedLocalContacts addObject:selectedContacts];
			[selectedContacts release];
		}else {
			for (int i = 0; i < [selectedLocalContacts count]; i++) {
				NSMutableDictionary *contact = [selectedLocalContacts objectAtIndex:i];
				if ([contact isEqualToDictionary:[localContacts objectAtIndex:indexPath.row]]) {
					[selectedLocalContacts removeObjectAtIndex:i];
					break;
				}
			}
			cell.accessoryType = UITableViewCellAccessoryNone;
		}	
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	[self changeOperationState];
}

#pragma mark ---- 事件处理方法 ----
- (void) selectAction: (id) sender {
	int index = [sender selectedSegmentIndex];
	if (index == 0) {
		//全选操作
		if (tabIndex == 0) {
			int count = [selectedRemoteContacts count];
			[selectedRemoteContacts removeAllObjects];
			if (count != [remoteContacts count]) {
				selectedRemoteContacts = [[MCUIToolkit getObjectCopy:remoteContacts] retain];
			}
		} else {
			int count = [selectedLocalContacts count];
			[selectedLocalContacts removeAllObjects];
			if (count != [localContacts count]) {
				selectedLocalContacts = [[MCUIToolkit getObjectCopy:localContacts] retain];
			}
		}
		[self.tableview reloadData];
		[self changeOperationState];
		return;
	}
	//导入和上传操作
	if (tabIndex == 0) {
		if ([selectedRemoteContacts count] == 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
															message:@"请选择需要导入的通讯录!"
														   delegate:nil
												  cancelButtonTitle:@"确定"
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
			return;
		}
		ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
		//取本地通讯录
		NSArray *peopleArray = (NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(iPhoneAddressBook);
		
		CFErrorRef error = NULL;
		//遍历选中的将要同步的远程通讯录
		for (NSMutableDictionary *contact in selectedRemoteContacts) {
			NSMutableDictionary *remoteContact = [contact objectForKey:@"data"];
			NSString *name = [[remoteContact objectForKey:@"name"] objectForKey:@"value"];
			/*
			bool replace = NO;
			//遍历本地通讯录进行匹配，如果存在则覆盖
			for (int i = 0; i < [peopleArray count]; i++) {
				ABRecordRef people = (ABRecordRef)[peopleArray objectAtIndex:i];
				ABMultiValueRef firstName = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonFirstNameProperty);
				if ([name isEqualToString:[NSString stringWithFormat:@"%@", firstName]]) {
					ABMultiValueRef multiPhones = ABRecordCopyValue(people, kABPersonPhoneProperty);
					ABMutableMultiValueRef multiPhonesList = ABMultiValueCreateMutableCopy(multiPhones);
					CFRelease(multiPhones);
					bool didReplace = ABMultiValueReplaceValueAtIndex(multiPhonesList, [[remoteContact objectForKey:@"mobile_tel"] objectForKey:@"value"], 0);
					if (didReplace) {
						ABRecordSetValue(people, kABPersonPhoneProperty, multiPhonesList, &error);
					}
					CFRelease(multiPhonesList);
				
					multiPhones = ABRecordCopyValue(people, kABPersonEmailProperty);
					multiPhonesList = ABMultiValueCreateMutableCopy(multiPhones);
					CFRelease(multiPhones);
					didReplace = ABMultiValueReplaceValueAtIndex(multiPhonesList, [[remoteContact objectForKey:@"e-mail"] objectForKey:@"value"], 0);
					if (didReplace) {
						ABRecordSetValue(people, kABPersonEmailProperty, multiPhonesList, &error);
					}
					CFRelease(multiPhonesList);
					ABAddressBookSave(iPhoneAddressBook, &error);
					replace = YES;
					break;
				}
			}
			if (replace) {
				continue;
			}*/
			
			//遍历本地通讯录进行匹配，如果存在则先删除
			for (int i = 0; i < [peopleArray count]; i++) {
				ABRecordRef people = (ABRecordRef)[peopleArray objectAtIndex:i];
				ABMultiValueRef firstName = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonFirstNameProperty);
				ABMultiValueRef lastName = (ABMultiValueRef)ABRecordCopyValue(people, kABPersonLastNameProperty);
				NSMutableString *strName = [NSMutableString string];
				if (firstName) [strName appendFormat:@"%@", firstName];
				if (lastName) [strName appendFormat:@"%@", lastName];
				
				if ([name isEqualToString:[NSString stringWithFormat:@"%@", strName]]) {
					ABAddressBookRemoveRecord(iPhoneAddressBook, people, &error);
					break;
				}
			}
			//如果本地通讯录不存在则新增
			ABRecordRef newPerson = ABPersonCreate();
			ABRecordSetValue(newPerson, kABPersonFirstNameProperty, name, &error);
			ABMultiValueRef phone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
			bool didAdd = ABMultiValueAddValueAndLabel(phone, [[remoteContact objectForKey:@"mobile_tel"] objectForKey:@"value"], kABPersonPhoneMobileLabel, NULL);
			if (didAdd) {
				ABRecordSetValue(newPerson, kABPersonPhoneProperty, phone, &error);
			}
			CFRelease(phone);
			phone = nil;
			
			if ([[remoteContact objectForKey:@"home_tel"] objectForKey:@"value"]) {
				phone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
				didAdd = ABMultiValueAddValueAndLabel(phone, [[remoteContact objectForKey:@"home_tel"] objectForKey:@"value"], kABHomeLabel, NULL);
				if (didAdd) {
					ABRecordSetValue(newPerson, kABPersonPhoneProperty, phone, &error);
				}
				CFRelease(phone);
				phone = nil;
			}
			
			if ([[remoteContact objectForKey:@"work_tel"] objectForKey:@"value"]) {
				phone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
				didAdd = ABMultiValueAddValueAndLabel(phone, [[remoteContact objectForKey:@"work_tel"] objectForKey:@"value"], kABWorkLabel, NULL);
				if (didAdd) {
					ABRecordSetValue(newPerson, kABPersonPhoneProperty, phone, &error);
				}
				CFRelease(phone);
				phone = nil;
			}
			
			if ([[remoteContact objectForKey:@"e-mail"] objectForKey:@"value"]) {
				phone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
				didAdd = ABMultiValueAddValueAndLabel(phone, [[remoteContact objectForKey:@"e-mail"] objectForKey:@"value"], kABHomeLabel, NULL);
				if (didAdd) {
					ABRecordSetValue(newPerson, kABPersonEmailProperty, phone, &error);
				}
				CFRelease(phone);
				phone = nil;
			}
			
			ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
			ABAddressBookSave(iPhoneAddressBook, &error);
			CFRelease(newPerson);	
		}
		CFRelease(iPhoneAddressBook);
		[selectedRemoteContacts removeAllObjects];
		[self.tableview reloadData];
		NSString *msg;
		if (error == NULL) {
			msg = @"通讯录导入成功!";
		}else {
			msg = @"通讯录导入异常!";
		}
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
														message:msg
													   delegate:nil
											  cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		[self changeOperationState];
	}else {
		if ([selectedLocalContacts count] == 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
															message:@"请选择需要上传的通讯录!"
														   delegate:nil
												  cancelButtonTitle:@"确定"
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
			return;
		}
		if (operateType) {
			[operateType release];operateType = nil;
		}
		operateType = [@"uploadContact" retain];
		[[MServerDAO sharedInstance] uploadContact:contactId 
										   records:selectedLocalContacts 
										  delegate:self];
	}
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if ([@"uploadContact" isEqualToString:operateType]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
														message:@"通讯录上传成功!"
													   delegate:nil
											  cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		[selectedLocalContacts removeAllObjects];
		[self.tableview reloadData];
		[self changeOperationState];
		if (operateType) {
			[operateType release];operateType = nil;
		}
		operateType = [@"downloadContact" retain];
		[[MServerDAO sharedInstance] downloadContact:contactId
												page:-1
											delegate:self];
	}else {
		self.remoteContacts = [returnValue objectForKey:@"rl"];
		[self.tableview reloadData];
	}
} 

@end
